package Listener;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import Util.MODE;

public class ShapeListener implements Listener{
	private String userID;
	private String[] mode;
	private int lastX;
	private int lastY;
	private int startX;
	private int startY;
	private String shape = MODE.SHAPE_CIRCLE;

	public ShapeListener(String[] mode, String userID){
		this.mode = mode;
		this.userID = userID;
		lastX = 0;
		lastY = 0;
	}

	@Override
	public void handleEvent(Event event) {
		GC gc;
		if(event.widget instanceof Canvas)
			gc = new GC((Canvas)event.widget);
		else
			gc = new GC(event.display);
		
		Canvas canvas;
		
		if(mode[MODE.MODE].equals(MODE.SHAPE)){
			int size = event.widget.getDisplay().getShells().length;
			
			switch(event.type){
			case SWT.Selection:
				shape = ((Button)event.widget).getData().toString();
				break;
			case SWT.MouseMove:
				lastX = event.x;
				lastY = event.y;
				break;

			case SWT.MouseDown:
				startX = event.x;
				startY = event.y;
				break;
			case SWT.MouseUp:

				if(size > 1){
					for(int i = 0; i < size; i++ ){
						for(int j = 0; j < event.widget.getDisplay().getShells()[i].getChildren().length; j++){
							if(event.widget.getDisplay().getShells()[i].getChildren()[j] instanceof Canvas){
								canvas = (Canvas)(event.widget.getDisplay().getShells()[i]).getChildren()[j];
								gc = new GC(canvas);
								
								if(shape.equals(MODE.SHAPE_CIRCLE)){
									gc.drawOval(startX, startY, lastX - startX, lastY - startY);
								}
								else if(shape.equals(MODE.SHAPE_RECTANGLE)){
									gc.drawRectangle(startX, startY, lastX - startX, lastY - startY);
								}
								else if(shape.equals(MODE.SHAPE_TRIANGLE)){
									int midPoint = (lastX + startX) / 2;
									gc.drawPolygon(new int[]{midPoint, startY, lastX, lastY, startX, lastY});
								}
								gc.drawString(userID + "             ", 10, 10);
							}
						}
					}
				}else{
					if(shape.equals(MODE.SHAPE_CIRCLE)){
						gc.drawOval(lastX, lastY, event.x - lastX, event.y - lastY);
					}
					else if(shape.equals(MODE.SHAPE_RECTANGLE)){
						gc.drawRectangle(lastX, lastY, event.x - lastX, event.y - lastY);
					}
					else if(shape.equals(MODE.SHAPE_TRIANGLE)){
						int midPoint = (lastX + event.x);
						gc.drawPolyline(new int[]{midPoint, lastY, event.x, event.y, lastX, event.y});
					}
				}
				gc.dispose();
				break;
			}
		}
	}

}
